package com.zengdb.jdbc.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.zengdb.jdbc.handler.ResultSetHandler;

public class JdbcTemplate {

	//私有化构造方法，禁止外部实例化当前类
	private JdbcTemplate(){}
	
	
	/**
	 * 执行DML语句的模板方法
	 * @param sql 需要执行的sql语句
	 * @param obj sql语句中预编译字段的值(0个或多个)
	 */
	public static void update(String sql,Object... obj){
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//获取数据库连接
			conn = JdbcUtil.getConnection();
			//获取执行sql语句的预编译对象
			ps = conn.prepareStatement(sql);
			//为预编译SQL语句中的字段赋值，执行sql语句
			
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i + 1, obj[i]);
			}
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			if (JdbcUtil.getConn() == null) {
				JdbcUtil.close(conn, ps, null);
			}else{ //JdbcUtil.getConn()不为null时，说明存在事务，则不要在此关闭连接对象。连接对象在事务提交或回滚时关闭
				JdbcUtil.close(null, ps, null); 
			}
		}
	}
	
	public static <T> T query(String sql, ResultSetHandler<T> rsh, Object... obj){
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i + 1, obj[i]);
			}
			rs = ps.executeQuery();
			return rsh.handler(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.close(conn, ps, rs);
		}
		return null;
	}
}
